#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import tkinter
import threading
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import platform

filepath = ""

def httpget(url):  # 未解码
    header = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3704.400 QQBrowser/10.4.3620.400'}
    html = requests.get(url=url,headers=header).content
    return html

def start(num):  # 启动 准备函数
    sj_zd = {}
    for i in range(10):
        api_url = 'https://www.moepro.cn/sjbz/list_' + str(num + i) + '.html'
        html = httpget(api_url)
        dom = BeautifulSoup(html,"html.parser")
        list = dom.select("div.zhuti_w_list >ul>li")
        for item in list:
            herf = item.a.get("href")
            title = item.em.text
            # print(title,herf)
            sj_zd[title] = herf
    return sj_zd  # 返回 一个 字典 标题 和 网址


def list_ins(zd):  # 给列表添加 数据
    for a in zd:
        l1.insert(0, a)
    pass

listnumber = 0 # 用来计算线程是否完成
def _did(): # 点击事件
    abc = l1.curselection()  # 获取当前选择项 （1：2） 位置
    key1 = l1.get(abc)
    var1.set(key1)
    ul = urljoin("https://www.moepro.cn/80286.html",zd_name_url[key1])
    # print(ul)
    htm = httpget(ul)
    dom = BeautifulSoup(htm, "html.parser")
    list = dom.select("div > img")
    for item in list:
        pngurl = item.get("src")
        abc = threading.Thread(target=dld, name=key1, args=(pngurl, key1, len(list)))
        abc.start()

def dld(png_url, name, numall): # 下载
    global listnumber , filepath
    listnumber +=1
    filename = png_url.split('/')[-1]
    if not os.path.exists(filepath):
        os.makedirs(filepath)
    os.chdir(filepath)
    img = httpget(png_url)
    with open(filename,"wb") as f:
        f.write(img)
    if numall == listnumber:
        var3.set('下载完成！保存在 '+filepath)
    else:
        var3.set('已完成：' + str(num))

pagenum = 1
def _xyy(): # 下一页
    global pagenum
    pagenum +=1
    var2.set(f"第{pagenum}页")
    to = start(int(pagenum))
    list_ins(to)
    pass  # 下一页 添加


def initpath():
    global filepath
    sys_platform = platform.platform().lower()
    if "windows" in sys_platform:
        filepath = 'D:\\动漫壁纸\\' + name + '\\'
        print("Windows",filepath)
    elif "macos" in sys_platform:
        print("Mac os")
    elif "linux" in sys_platform:
        filepath = "~/壁纸/"
        print("Linux",filepath)
    else:
        print("其他系统")

if __name__ == "__main__":
    initpath()
    zhu = tkinter.Tk()
    zhu.title('动漫电脑壁纸批量下载器！！！')
    zhu.geometry('600x400+200+60')
    b1 = tkinter.Button(zhu, text='下载', command=_did)
    b1.place(width=60, height=40, x=310, y=10)
    b2 = tkinter.Button(zhu, text='下一页', command=_xyy)
    b2.place(width=90, height=40, x=380, y=10)
    var1 = tkinter.StringVar()
    var1.set('软件开启中 请稍后。。。')
    var2 = tkinter.StringVar()
    var2.set('第1页')
    var3 = tkinter.StringVar()
    var3.set('0')
    lb1 = tkinter.Label(zhu, textvariable=var1)
    lb1.place(width=280, height=60, x=310, y=60)
    lb2 = tkinter.Label(zhu, textvariable=var2)
    lb2.place(width=60, height=60, x=330, y=100)
    lb3 = tkinter.Label(zhu, textvariable=var3)
    lb3.place(width=230, height=60, x=310, y=140)

    l1 = tkinter.Listbox(zhu)
    l1.place(height=380, width=280, x=10, y=10)  # 设置 宽高 位置 300 x 400

    zd_name_url = start(1)
    list_ins(zd_name_url)

    zhu.mainloop()
